package com.wtx.chapter11;

/**
 * @description: 第一版的并查集
 * @author: wtx
 * @createDate: 2020/6/1
 */
public class UnionFind1 implements UF {

    private int[] ids;

    public UnionFind1(int size) {
        ids = new int[size];
        for (int i = 0; i < ids.length; i++)
            ids[i] = i;     // 每个元素都属于各自的集合, 没有相连
    }

    @Override
    public int getSize(){
        return ids.length;
    }

    //查找元素p对应的编号
    private int find(int p){
        if (p<0 || p>=ids.length)
            throw new IllegalArgumentException("p is out of bound");
        return ids[p];
    }


    //查看元素p、q是否属于一个集合
    @Override
    public boolean isConnected(int p, int q) {

        return find(p) == find(q);
    }

    //合并元素p、q所属的集合
    @Override
    public void unionElements(int p, int q) {

        int pId = find(p);
        int qId = find(q);

        if (pId == qId)
            return;

        for (int i = 0; i < ids.length; i++) {
            if (ids[i] == pId)
                ids[i] = qId;
        }
    }

}
